#include "widget.h"
#include "signin.h"
#include "signup.h"

int widget(int lcdp[][800])
{
	FILE *pic = fopen("./res/board.bmp", "r");
	if (pic == NULL)
	{
		printf("board open fail\n");
		return -1;
	}
	unsigned char buf[480][800 * 3] = {0};
	fseek(pic, 54, SEEK_SET);
	fread(buf, 3, 480 * 800, pic);
	for (int i = 0; i < 480; i++)
		for (int j = 0; j < 800; j++)
		{
			int y = 479 - i;
			lcdp[y][j] = 0x00 << 24 | buf[i][j * 3 + 2] << 16 | buf[i][j * 3 + 1] << 8 | buf[i][j * 3];
		}
	int lcdt = open("/dev/input/event0", O_RDWR);
	if (lcdt < 0)
	{
		perror("input error\n");
		return -1;
	}
	struct input_event touch;
	int x = -1, y = -1;
	int sinreturn = 0, siureturn = 0;
	while (1)
	{
		int read_ret = read(lcdt, &touch, sizeof(struct input_event));
		if (read_ret < 0)
		{
			perror("read touch failed\n");
			return -1;
		}
		if (touch.type == EV_ABS)
		{
			if (touch.code == ABS_X)
				x = touch.value * 800 / 1024;
			else if (touch.code == ABS_Y)
			{
				y = touch.value * 480 / 600;
			}
		}
		printf("x=%d y=%d\n", x, y);
		if (touch.type == EV_KEY)
		{
			if (touch.code == BTN_TOUCH && touch.value == 1)
			{
				if ((x > 275 && x < 510) && (y > 160 && y < 210))
				{
					printf("登入\n");
					sinreturn = signin(lcdp);
					if (sinreturn < 0)
						goto done;
					else if (sinreturn == 1)
						goto sinsucdone;
				}
				else if ((x > 275 && x < 510) && (y > 240 && y < 270))
				{
					printf("注册\n");
					siureturn = signup(lcdp);
					if (siureturn < 0)
						goto done;
					else if (siureturn == 1)
					{
						goto sucdone;
					}
				}
				else if ((x > 0 && x < 70) && (y > 410 && y < 480))
					goto exitdone;
			}
		}
	}
done:
	close(lcdt);
	fclose(pic);
	return -1;
sucdone:
	close(lcdt);
	fclose(pic);
	return 0;
sinsucdone:
	close(lcdt);
	fclose(pic);
	return 1;
exitdone:
	close(lcdt);
	fclose(pic);
	return -2;
}